package com.kunsan.compose.utils

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type

object GsonUtils {

    private var GSON: Gson

    fun getGson() = GSON

    init {
        val builder = GsonBuilder()
        GSON = builder.setPrettyPrinting()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
            .create()
    }

    @JvmStatic
    fun <T> fromJson(data: String?, type: Type?): T? {
        try {
            return GSON.fromJson(data, type)
        } catch (e: Exception) {
        }
        return null
    }

    @JvmStatic
    fun <T> fromJson(data: String?, typeToken: TypeToken<*>?): T? {
        try {
            return fromJson(data, typeToken?.type)
        } catch (e: Exception) {
        }
        return null
    }

    @JvmStatic
    fun <T> fromJson(data: String?, clz: Class<T>?): T? {
        if (data == null) {
            return null
        }
        try {
            return GSON.fromJson(data, clz)
        } catch (e: Exception) {
        }
        return null
    }

    @JvmStatic
    fun toJson(src: Any?): String? {
        src ?: return null
        if (src is String) {
            return src
        }
        try {
            return GSON.toJson(src)
        } catch (e: StackOverflowError) {
            val msg = String.format(
                "[%s] is not a valid json object",
                src.javaClass.name
            )
        } catch (e: Exception) {
        }
        return null
    }

}